﻿using ILCalc;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;

namespace Function_Analyzer.MathUtil
{
    class MathCal
    {
        private static string[] exps = new string[3];
        public static bool error;  //check if have any error when valuation

        public static void Init(string exp, int index)
        {
            exps[index] = exp;
        }

        public static double Evaluate(string exp)
        {
            var calc = new CalcContext<double>();
            calc.Constants.ImportBuiltIn();
            calc.Functions.ImportBuiltIn();

            return calc.Evaluate(exp);
        }

        public static double GetVal(double x, int index)
        {
            string exp=Util.ReplaceVar(exps[index],'x',x.ToString());
            return Val(exp);
        }

        public static string StrGetVal(double x, int index)
        {
            error = false;
            string exp = Util.ReplaceVar(exps[index], 'x', x.ToString());
            try
            {
                return Evaluate(exp).ToString();
            }
            catch (Exception e)
            {
                error = true;
                return "Error";
            }
        }

        //return 0 if invalid
        public static double Val(string exp)
        {
            error = false;
            try
            {
                return Evaluate(exp);
            }
            catch (Exception e)
            {
                error = true;
                return 0;
            }
        }

        
    }
}
